﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;

namespace Helpers
{
    public static class Processes
    {
        public static Process GetActiveWindowProcess()
        {
            string text = Processes.GetActiveWindowTitle();

            return Process.GetProcesses().First(proc => proc.MainWindowTitle == text);
        }
        private static string GetActiveWindowTitle()
        {
            StringBuilder buf = new StringBuilder(256);
            IntPtr handle = Processes.GetForegroundWindow();

            if (Processes.GetWindowText(handle, buf, 256) > 0)
                return buf.ToString();

            return null;
        }
        [DllImport("user32.dll")]
        private static extern IntPtr GetForegroundWindow();
        [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern int GetWindowText(IntPtr hWnd, System.Text.StringBuilder lpString, int nMaxCount);
        [DllImport("User32.dll")]
        public static extern int SetForegroundWindow(IntPtr hWnd);

    }
}
